package org.mx.dal.test.config;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

@SuppressWarnings("javadoc")
@Configuration
@EnableJpaRepositories(basePackages = "org.mx.dal.test.repository.two", entityManagerFactoryRef = "twoEntityManagerFactory", transactionManagerRef = "twoTransactionManager")
public class TwoTransactionConfig {
	@Autowired
	@Qualifier("dsTwo")
	private DataSource dsTwo;

	@Resource
	private JpaProperties jpaProperties;

	@Bean(name = "twoEntityManagerFactory")
	@Primary
	public LocalContainerEntityManagerFactoryBean oneEntityFactory(EntityManagerFactoryBuilder builder) {
		return builder.dataSource(dsTwo).properties(jpaProperties.getProperties())
				.packages("org.mx.dal.test.entity.two").persistenceUnit("persistence-two").build();
	}

	@Bean(name = "twoTransactionManager")
	@Primary
	public PlatformTransactionManager transactionManager(LocalContainerEntityManagerFactoryBean entityManagerFactory) {
		return new JpaTransactionManager(entityManagerFactory.getObject());
	}
}
